﻿using LicenseApp.Client;
using LicenseApp.Test;

Console.WriteLine("=== 授权系统测试程序 ===");
Console.WriteLine();

Console.WriteLine("选择测试模式:");
Console.WriteLine("1. 基本功能测试");
Console.WriteLine("2. 端到端完整测试");
Console.WriteLine("3. 非阻塞通知测试");
Console.WriteLine("4. 授权码调试分析");
Console.WriteLine("5. 使用天数调试分析 (旧方案)");
Console.WriteLine("6. 简洁时间防护测试 (新方案)");
Console.WriteLine("7. 机器码和授权码验证");
Console.WriteLine("8. 文件写入权限测试");
Console.WriteLine("请输入选择 (1-8): ");

string? choice = Console.ReadLine();

switch (choice)
{
    case "1":
        TestClientLibrary();
        break;
    case "2":
        EndToEndTest.RunTest();
        break;
    case "3":
        TestNotifications();
        break;
    case "4":
        TestLicenseDebugger();
        break;
    case "5":
        TestUsageDebugger();
        break;
    case "6":
        TestSimpleTimeGuard();
        break;
    case "7":
        TestMachineCodeAndLicense();
        break;
    case "8":
        TestFileWrite();
        break;
    default:
        Console.WriteLine("无效选择，运行基本功能测试...");
        TestClientLibrary();
        break;
}

static void TestClientLibrary()
{
    Console.WriteLine("1. 测试客户端库基本功能");

    // 模拟公钥（实际使用时应该从生产工具获取）
    string samplePublicKey = @"<RSAKeyValue>
<Modulus>test_modulus_here</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>";

    Console.WriteLine("   - 初始化授权系统...");
    // 注意：这里使用示例公钥，实际使用时需要从生产工具获取真实公钥
    // var initResult = LicenseManager.Initialize(samplePublicKey);
    // Console.WriteLine($"   - 初始化结果: {(initResult ? "成功" : "失败")}");

    Console.WriteLine("   - 检查当前授权状态...");
    var isValid = LicenseManager.IsLicenseValid();
    Console.WriteLine($"   - 当前授权状态: {(isValid ? "有效" : "无效")}");

    var licenseInfo = LicenseManager.GetLicenseInfo();
    if (licenseInfo != null)
    {
        Console.WriteLine($"   - 授权信息:");
        Console.WriteLine($"     生效日期: {licenseInfo.StartDate:yyyy-MM-dd}");
        Console.WriteLine($"     授权天数: {licenseInfo.Days}");
        Console.WriteLine($"     AGV数量: {licenseInfo.AgvCount}");
        Console.WriteLine($"     结束日期: {licenseInfo.EndDate:yyyy-MM-dd}");
        Console.WriteLine($"     剩余天数: {licenseInfo.RemainingDays}");
        Console.WriteLine($"     即将到期: {(licenseInfo.IsExpiringSoon ? "是" : "否")}");
    }
    else
    {
        Console.WriteLine("   - 未找到有效的授权信息");
    }

    Console.WriteLine();
    Console.WriteLine("2. 测试监控功能");

    var monitor = LicenseManager.StartMonitoring();

    // 注册事件处理
    monitor.LicenseStatusChanged += (sender, e) =>
    {
        Console.WriteLine($"   [事件] 授权状态变化: {(e.IsValid ? "有效" : "无效")}");
    };

    monitor.LicenseExpiring += (sender, e) =>
    {
        Console.WriteLine($"   [提醒] 授权即将到期，剩余 {e.RemainingDays} 天");
    };

    monitor.LicenseExpired += (sender, e) =>
    {
        Console.WriteLine($"   [警告] 授权已失效");
    };

    Console.WriteLine("   - 监控已启动，等待5秒...");
    Thread.Sleep(5000);

    Console.WriteLine("   - 停止监控");
    LicenseManager.StopMonitoring();

    Console.WriteLine();
    Console.WriteLine("=== 测试完成 ===");
    Console.WriteLine();
    Console.WriteLine("使用说明:");
    Console.WriteLine("1. 运行生产工具 (LicenseApp.Producer)");
    Console.WriteLine("2. 创建客户并生成密钥对");
    Console.WriteLine("3. 生成授权码");
    Console.WriteLine("4. 将公钥文件复制到客户端应用目录");
    Console.WriteLine("5. 在客户端应用中调用 LicenseManager.Initialize(publicKeyXml)");
    Console.WriteLine("6. 调用 LicenseManager.RegisterLicense(licenseCode) 注册授权码");
    Console.WriteLine("7. 使用 LicenseManager.IsLicenseValid() 检查授权状态");
}

static void TestNotifications()
{
    Console.WriteLine("=== 非阻塞通知测试 ===");
    Console.WriteLine();

    Console.WriteLine("1. 测试控制台通知器");
    var consoleNotifier = new ConsoleNotifier();
    consoleNotifier.ShowNotification("这是一个测试消息", LicenseStatus.Valid);
    consoleNotifier.ShowExpiringNotification(5);
    consoleNotifier.ShowExpiredNotification();

    Console.WriteLine();
    Console.WriteLine("2. 测试日志文件通知器");
    var logNotifier = new LogFileNotifier();
    logNotifier.ShowNotification("日志测试消息", LicenseStatus.ExpiringSoon);
    Console.WriteLine("   日志已写入到 license_notifications.log");

    Console.WriteLine();
    Console.WriteLine("3. 测试LicenseManager的通知功能");

    // 设置控制台通知器（因为在控制台环境中）
    LicenseManager.SetNotifier(consoleNotifier);

    // 测试各种通知
    LicenseManager.ShowNotification("授权系统初始化完成", LicenseStatus.Valid);
    LicenseManager.ShowNotification("授权即将到期", LicenseStatus.ExpiringSoon);
    LicenseManager.ShowNotification("授权在宽限期内", LicenseStatus.ExpiredGracePeriod);
    LicenseManager.ShowNotification("授权已过期", LicenseStatus.Expired);

    Console.WriteLine();
    Console.WriteLine("4. 如果在WPF应用中，会显示自定义通知窗口");
    Console.WriteLine("   控制台应用自动使用控制台通知器");

    Console.WriteLine();
    Console.WriteLine("=== 通知测试完成 ===");
}

static void TestLicenseDebugger()
{
    Console.WriteLine("=== 授权码调试工具 ===");
    Console.WriteLine();

    Console.WriteLine("请选择调试模式:");
    Console.WriteLine("1. 分析指定授权码");
    Console.WriteLine("2. 测试授权码注册");
    Console.WriteLine("请输入选择 (1-2): ");

    string? debugChoice = Console.ReadLine();

    Console.WriteLine();
    Console.WriteLine("请输入授权码:");
    string? licenseCode = Console.ReadLine();

    if (string.IsNullOrWhiteSpace(licenseCode))
    {
        Console.WriteLine("授权码不能为空");
        return;
    }

    Console.WriteLine();

    switch (debugChoice)
    {
        case "1":
            LicenseDebugger.AnalyzeLicenseCode(licenseCode);
            break;
        case "2":
            LicenseDebugger.TestLicenseRegistration(licenseCode);
            break;
        default:
            Console.WriteLine("无效选择，执行分析...");
            LicenseDebugger.AnalyzeLicenseCode(licenseCode);
            break;
    }
}

static void TestUsageDebugger()
{
    Console.WriteLine("=== 使用天数调试工具 ===");
    Console.WriteLine();

    Console.WriteLine("请选择操作:");
    Console.WriteLine("1. 分析当前使用天数问题");
    Console.WriteLine("2. 清理异常使用记录");
    Console.WriteLine("请输入选择 (1-2): ");

    string? choice = Console.ReadLine();

    Console.WriteLine();

    switch (choice)
    {
        case "1":
            UsageDebugger.AnalyzeUsageDays();
            break;
        case "2":
            Console.WriteLine("⚠️  警告: 此操作将删除所有使用记录文件，下次启动时将重新计算使用天数");
            Console.WriteLine("确定要继续吗？请输入 'yes' 确认:");
            UsageDebugger.CleanupUsageRecords();
            break;
        default:
            Console.WriteLine("无效选择，执行分析...");
            UsageDebugger.AnalyzeUsageDays();
            break;
    }
}

static void TestSimpleTimeGuard()
{
    Console.WriteLine("=== 简洁时间防护测试 ===");
    Console.WriteLine();

    Console.WriteLine("请选择操作:");
    Console.WriteLine("1. 测试新的简洁方案");
    Console.WriteLine("2. 清理时间记录文件");
    Console.WriteLine("请输入选择 (1-2): ");

    string? choice = Console.ReadLine();

    Console.WriteLine();

    //switch (choice)
    //{
    //    //case "1":
    //    //    SimpleTimeGuardTest.TestSimpleTimeGuard();
    //    //    break;
    //    case "2":
    //        Console.WriteLine("⚠️  警告: 此操作将删除时间记录文件，下次启动时将重新初始化");
    //        Console.WriteLine("确定要继续吗？请输入 'yes' 确认:");
    //        var confirm = Console.ReadLine();
    //        if (confirm?.ToLower() == "yes")
    //        {
    //            SimpleTimeGuardTest.CleanTimeRecords();
    //        }
    //        else
    //        {
    //            Console.WriteLine("操作已取消");
    //        }
    //        break;
    //    default:
    //        Console.WriteLine("无效选择，执行测试...");
    //        SimpleTimeGuardTest.TestSimpleTimeGuard();
    //        break;
    //}
}

static void TestMachineCodeAndLicense()
{
    Console.WriteLine("=== 机器码和授权码验证 ===");
    Console.WriteLine();

    Console.WriteLine("请选择操作:");
    Console.WriteLine("1. 检查当前机器码");
    Console.WriteLine("2. 测试授权码验证");
    Console.WriteLine("请输入选择 (1-2): ");

    string? choice = Console.ReadLine();

    Console.WriteLine();

    switch (choice)
    {
        case "1":
            MachineCodeChecker.CheckCurrentMachineCode();
            break;
        case "2":
            MachineCodeChecker.TestLicenseValidation();
            break;
        default:
            Console.WriteLine("无效选择，执行机器码检查...");
            MachineCodeChecker.CheckCurrentMachineCode();
            break;
    }
}

static void TestFileWrite()
{
    Console.WriteLine("=== 文件写入权限测试 ===");
    Console.WriteLine();

    Console.WriteLine("请选择操作:");
    Console.WriteLine("1. 测试文件写入权限");
    Console.WriteLine("2. 检查进程占用情况");
    Console.WriteLine("3. 清理测试文件");
    Console.WriteLine("请输入选择 (1-3): ");

    string? choice = Console.ReadLine();

    Console.WriteLine();

    switch (choice)
    {
        case "1":
            FileWriteTest.TestFileWrite();
            break;
        case "2":
            FileWriteTest.CheckProcessUsage();
            break;
        case "3":
            Console.WriteLine("⚠️  警告: 此操作将删除所有测试文件");
            Console.WriteLine("确定要继续吗？请输入 'yes' 确认:");
            var confirm = Console.ReadLine();
            if (confirm?.ToLower() == "yes")
            {
                FileWriteTest.CleanupTestFiles();
            }
            else
            {
                Console.WriteLine("操作已取消");
            }
            break;
        default:
            Console.WriteLine("无效选择，执行文件写入测试...");
            FileWriteTest.TestFileWrite();
            break;
    }
}
